﻿using System;
using System.Collections;
using System.Collections.Generic;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;

namespace Yoozoo.Gameplay.Liberty.StreetEvent
{
    public class AddNpcGroup : LatentActionNodeBase
    {
        [Serializable]
        public class Npc
        {
            public int npcId;               // npcId 对应 rpg_npc配表
            public string pointName;
            public string animState;
            public SideType sideType;
        }
        
        public BBParameter<List<AddNpcGroup.Npc>> npcConfigs;
        protected List<AIBirthData> _aiBirthDataList;
        
        public IEnumerator Invoke()
        {
            _aiBirthDataList = new List<AIBirthData>();
            if (npcConfigs.value != null)
            {
                foreach (var npcConfig in npcConfigs.value)
                {
                    BluePrintPoint point = BlueprintUtils.GetBlueprintPoint(npcConfig.pointName);
                    if (point != null)
                    {
                        AIBirthData birthData = new AIBirthData();
                        birthData.uniqueId = NpcUniqueIdUtils.GetEventNpcUniqueID();
                        birthData.position = point.position;
                        birthData.forward = point.forward;
                        birthData.modelResId = npcConfig.npcId;
                        birthData.animState = npcConfig.animState;
                        birthData.sideType = npcConfig.sideType;
                        birthData.isStreetEvent = true;
                        birthData.isStatic = false;
                        LibertyAIUtils.AIManager.AddNpc(birthData, 1002);
                        _aiBirthDataList.Add(birthData);
                        
                        yield return new WaitForOneFrame();
                    }
                }
            }
        }
        
        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            node.AddFlowInput("In", (f) => { Begin(Invoke(), f); });
        }
        
        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            if (_aiBirthDataList!=null)
            {
                foreach (var birthData in _aiBirthDataList)
                {
                    if (LibertyAIUtils.AIManager)
                    {
                        LibertyAIUtils.AIManager.RemoveNpc(birthData.uniqueId);
                    }
                }
            }
        }
    }
}